<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>我的订单</p>
    </header>
    <!-- 订单列表部分 -->
    <h3>未支付订单信息：</h3>
    <ul class="order" v-if="isDataLoaded && orderArr.length > 0">
      <template v-for="item1 in orderArr">
        <li v-if="item1 && item1.orderState === 0">
          <div class="order-info">
            <p>
              {{ item1.business.businessName }}
              <i class="fa fa-caret-down" @click="detailetShow(item1)"></i>
            </p>
            <div class="order-info-right">
              <p>&#165;{{ item1.savedOrderTotal }}</p> <!-- 使用保存的订单总价 -->
              <div class="order-info-right-icon"  @click="topayment(item1)">去支付</div>
            </div>
          </div>
          <ul class="order-detailet" v-show="item1.isShowDetailet">
            <li v-for="odItem1 in item1.list">
              <p>{{ odItem1.food.foodName }} x {{ odItem1.quantity }}</p>
              <p>&#165;{{ odItem1.savedFoodPrice * odItem1.quantity }}</p> <!-- 使用保存的价格 -->
            </li>
            <li>
              <p>配送费</p>
              <p>&#165;{{ item1.savedDeliveryPrice }}</p> <!-- 使用保存的配送费 -->
            </li>
          </ul>
        </li>
      </template>
    </ul>
    <h3>已支付订单信息：</h3>
    <ul class="order" v-if="orderArr.length > 0">
      <template v-for="item1 in orderArr">
        <li v-if="item1 && item1.orderState === 1">
          <div class="order-info">
            <p>
              {{ item1.business.businessName }}
              <i class="fa fa-caret-down" @click="detailetShow(item1)"></i>
            </p>
            <div class="order-info-right">
              <p>&#165;{{ item1.savedOrderTotal }}</p> <!-- 使用保存的订单总价 -->
              <div class="order-info-right-icon-icon">已支付</div>
            </div>
          </div>
          <ul class="order-detailet" v-show="item1.isShowDetailet">
            <li v-for="odItem1 in item1.list">
              <p>{{ odItem1.food.foodName }} x {{ odItem1.quantity }}</p>
              <p>&#165;{{ odItem1.savedFoodPrice * odItem1.quantity }}</p> <!-- 使用保存的价格 -->
            </li>
            <li>
              <p>配送费</p>
              <p>&#165;{{ item1.savedDeliveryPrice }}</p> <!-- 使用保存的配送费 -->
            </li>
          </ul>
        </li>
      </template>
    </ul>

    <div>
      <h3 class="title" style="color: #000">{{}}</h3>
    </div>
    <!-- 底部菜单部分 -->
    <Footer></Footer>
  </div>
</template>

<script>
import {
  ref,
  onMounted
} from 'vue';
import Footer from '../components/Footer.vue';
import axios from 'axios';
import qs from 'qs';
import {
  getSessionStorage,
  setLocalStorage,
  getLocalStorage
} from '@/common';
import {
  useRoute,
  useRouter
} from 'vue-router';

export default {
  name: 'OrderList',
  components: {
    Footer
  },
  setup() {
    const orderArr = ref([]);
    const user = ref(getSessionStorage('user'));
    const isDataLoaded = ref(false);
    const orderId = ref(0);
    const route = useRoute();
    const router = useRouter();

    onMounted(() => {
      axios
          .post('/OrdersController/listOrdersByUserId', qs.stringify({
            userId: user.value.userId
          }))
          .then(response => {
            let result = response.data;

            for (let orders of result) {
              orders.isShowDetailet = false;

              // 从 localStorage 获取保存的订单数据
              let savedOrder = getLocalStorage(`order_${orders.orderId}`);

              // 如果没有保存过该订单的数据，则将当前订单信息保存到 localStorage
              if (!savedOrder) {
                const orderToSave = {
                  orderTotal: orders.orderTotal,
                  deliveryPrice: orders.business.deliveryPrice,
                  list: orders.list.map(odItem => ({
                    foodId: odItem.food.foodId,
                    savedFoodPrice: odItem.food.foodPrice,
                    quantity: odItem.quantity
                  }))
                };
                setLocalStorage(`order_${orders.orderId}`, orderToSave);
                savedOrder = orderToSave;
              }

              // 使用 localStorage 中的订单价格信息
              orders.savedOrderTotal = savedOrder.orderTotal;
              orders.savedDeliveryPrice = savedOrder.deliveryPrice;

              for (let odItem of orders.list) {
                const savedItem = savedOrder.list.find(savedOdItem => savedOdItem.foodId === odItem.food.foodId);
                if (savedItem) {
                  odItem.savedFoodPrice = savedItem.savedFoodPrice;
                  odItem.subTotal = savedItem.savedFoodPrice * savedItem.quantity;
                }
              }
            }

            orderArr.value = result;
            isDataLoaded.value = true;
          })
          .catch(error => {
            console.error(error);
          });
    });


    const detailetShow = async (orders) => {
      orders.isShowDetailet = !orders.isShowDetailet;
    };

    // 增加跳转支付界面
    const topayment = (orders) => {
      router.push({
        path: '/payment',
        query: {
          orderId: orders.orderId,
          userId: user.value.userId // 通过 ref 获取 userId 确保传递 userId，能通过userId查出积分
        }
      });
    };

    return {
      orderArr,
      user,
      isDataLoaded,
      detailetShow,
      topayment,
    };
  }
};
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;

  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;

  display: flex;
  justify-content: center;
  align-items: center;
}

/****************** 历史订单列表部分 ******************/
.wrapper h3 {
  margin-top: 12vw;
  box-sizing: border-box;
  padding: 4vw;
  font-size: 4vw;
  font-weight: 300;
  color: #999;
}

.wrapper .order {
  width: 100%;
}

.wrapper .order li {
  width: 100%;
}

.wrapper .order li .order-info {
  box-sizing: border-box;
  padding: 2vw 4vw;
  font-size: 4vw;
  color: #666;

  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .order li .order-info .order-info-right {
  display: flex;
}

.wrapper .order li .order-info .order-info-right .order-info-right-icon {
  background-color: #f90;
  color: #fff;
  border-radius: 3px;
  user-select: none;
  cursor: pointer;
}

.wrapper .order li .order-info .order-info-right .order-info-right-icon-icon {
  background-color: #00c957;
  color: #fff;
  border-radius: 3px;
  user-select: none;
  cursor: pointer;
}

.wrapper li .order-detailet {
  width: 100%;
}

.wrapper li .order-detailet li {
  width: 100%;
  box-sizing: border-box;
  padding: 1vw 4vw;
  color: #666;
  font-size: 3vw;

  display: flex;
  justify-content: space-between;
  align-items: center;
}

</style>
